const record = require('node-record-lpcm16');

class AudioRecorder {
  constructor(asr) {
    this.asr = asr;
    this.recording = null;
    this.testMode = process.platform === 'win32'; // Windows 上启用测试模式
  }

  start() {
    if (this.testMode) {
      console.log('Windows 测试模式：跳过实际录音，仅测试 ASR 连接...');
      console.log('ASR 连接测试完成。如需实际录音功能，请安装 sox:');
      console.log('1. 下载: https://sourceforge.net/projects/sox/files/sox/14.4.2/sox-14.4.2-win32.exe');
      console.log('2. 安装后将 sox.exe 添加到系统 PATH');
      console.log('3. 重新启动应用');
      return;
    }

    console.log('开始录音...');

    // 根据系统选择录音程序
    const recordProgram = process.platform === 'win32' ? 'sox' :
                         process.platform === 'linux' ? 'arecord' : 'rec';

    try {
      this.recording = record.record({
        sampleRateHertz: 16000,
        threshold: 0,
        verbose: false,
        recordProgram: recordProgram,
        silence: '1.0s'
      });

      this.recording.stream().on('data', (chunk) => {
        if (this.asr.isConnected) {
          this.asr.sendAudioData(chunk);
        }
      });

      this.recording.stream().on('error', (error) => {
        console.error('录音错误:', error);
      });
    } catch (error) {
      console.error('录音初始化失败:', error);
      console.log('请确保已安装音频录制工具 (sox/arecord)');
    }
  }

  stop() {
    if (this.recording) {
      console.log('停止录音...');
      this.recording.stop();
      this.recording = null;
    }
  }
}

module.exports = AudioRecorder;
